﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace PimImporter
{
    public partial class FrmMain : Form
    {
        internal static Mapper mapper;

        public FrmMain()
        {
            InitializeComponent();
            this.Name = Def.appName;
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            mapper = new Mapper();
            BtnDir.Height = TxbDir.Height;
        }

        private void BtnDir_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog dlg = new OpenFileDialog();
                dlg.Filter = "Contact files (*.csv)|*.csv";
                dlg.FilterIndex = 0;
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    if (Path.GetExtension(dlg.FileName).ToLower() != ".csv")
                    {
                        return;
                    }
                    TxbDir.Text = dlg.FileName;
                }
                BtnImport.Enabled = TxbDir.Text != "";
            }
            catch (Exception ex)
            {
                string err = ex.Message + (ex.InnerException != null ? ("\r\n" + ex.InnerException.Message) : "");
                MessageBox.Show(err, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);
            }
        }

        private void BtnImport_Click(object sender, EventArgs e)
        {
            try
            {
                if (TxbDir.Text != "")
                {
                    Importer importer = new Importer(TxbDir.Text, ChkFirstLine.Checked);
                    int[] res = importer.Import();
                    if (res[0] != -1)
                    {
                        string msg = res[0] + " contacts imported";
                        if (res[1] != 0)
                        {
                            msg += "\r\n" + res[1] + " errors occurred\r\nfor info see log file " + Def.errorFile;
                        }
                        MessageBox.Show(msg);
                    }
                }
            }
            catch (Exception ex)
            {
                string err = ex.Message + (ex.InnerException != null ? ("\r\n" + ex.InnerException.Message) : "");
                MessageBox.Show(err, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);
            }
        }
    }
}